<!-- components/ChatRoom.vue -->
<template>
  <div class="chat-room">
    <div class="message-list" ref="messageList">
      <div v-for="(msg, index) in chatsList" :key="index">
        <div v-if="msg.user == messages.roomId" class="message-item">
          <img class="avatar" :src="msg.url" alt="avatar" />
          <div class="message-content">
            <p class="username">{{ msg.user }}</p>
            <p class="message">{{ msg.info }}</p>
            <p class="message">{{ msg.message }}</p>
          </div>
        </div>
        <div v-else class="message-item">
          <div class="message-content" style="text-align: right;">
            <p class="username">{{ msg.user }}</p>
            <p class="message">{{ msg.info || msg.message }}</p>
          </div>
          <img class="avatar" :src="msg.url" alt="avatar" style="margin-left: 10rem;" />
        </div>
      </div>
    </div>

    <div class="input-bar">
      <input type="text" v-model="inputValue" placeholder="请输入消息" @input="onInput" />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup>
import { loadMessages, updateChats } from '@/utils/jia-axios'
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute } from 'vue-router';
const route = useRoute();

const messages = ref([])
const chatsList = ref([])

const messageList = ref(null); // 获取消息列表的 DOM 元素


const inputValue = ref('')

// 输入框事件
const onInput = (event) => {
  inputValue.value = event.target.value;
}

// 加载聊天信息
loadMessages(route.query.roomId).then(res => {
  // console.log("loadMessages", res.data.list[0].chatsList);
  messages.value = res.data.list[0]
  chatsList.value = res.data.list[0].chatsList
  nextTick(() => {
    if (messageList.value) {
      // 设置 scrollTop 为滚动容器的高度
      messageList.value.scrollTop = messageList.value.scrollHeight;
    }
  });
})

const ws = ref(null);           // WebSocket 实例

// 初始化 WebSocket
const initWebSocket = () => {
  ws.value = new WebSocket('ws://localhost:3300');

  ws.value.onopen = function () {
    // 客户端加入房间
    const joinMessage = JSON.stringify({ type: 'message', action: 'join', roomId: route.query.roomId });
    ws.value.send(joinMessage);
  };

  ws.value.onmessage = function (event) {
    const data = JSON.parse(event.data);
    // console.log('Received message:', data.message);

    setTimeout(() => {
      loadMessages(route.query.roomId).then(res => {
        // console.log("loadMessages", res.data);
        messages.value = res.data.list[0]
        chatsList.value = res.data.list[0].chatsList
        nextTick(() => {
          if (messageList.value) {
            // 设置 scrollTop 为滚动容器的高度
            messageList.value.scrollTop = messageList.value.scrollHeight;
          }
        });
      })
    }, 500)
  };


  ws.value.onclose = () => {
    console.log('WebSocket 连接已关闭');
  };

  ws.value.onerror = (error) => {
    console.error('WebSocket 错误:', error);
  };
};
// 发送消息
const sendMessage = () => {
  if (inputValue.value.trim() === '') return;  // 输入为空时不发送消息

  // 在此处，你可以通过 WebSocket 或 HTTP 请求将消息发送到服务器
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    const message = JSON.stringify({
      type: "message",
      roomId: route.query.roomId,
      user: '67767f17e1006c39f3902ae1',
      url: "http://localhost:3000/work-2.jpg",
      message: inputValue.value
    })
    chatsList.value = [...chatsList.value, JSON.parse(message)]
    ws.value.send(message);
    console.log('已发送消息:', chatsList.value);
    updateChats(route.query.roomId, chatsList.value).then(res => {
      loadMessages(route.query.roomId).then(res => {
        // console.log("loadMessages", res.data);
        messages.value = res.data.list[0]
        chatsList.value = res.data.list[0].chatsList
        nextTick(() => {
          if (messageList.value) {
            // 设置 scrollTop 为滚动容器的高度
            messageList.value.scrollTop = messageList.value.scrollHeight;
          }
        });
      })
    })
    inputValue.value = '';  // 清空输入框
  } else {
    console.error('WebSocket 未连接');
  }
}
// 初始化 WebSocket 连接
onMounted(() => {
  initWebSocket();
});

// 组件卸载时关闭 WebSocket 连接
onUnmounted(() => {
  if (ws.value) {
    ws.value.close();
  }
});

</script>

<style scoped>
.chat-room {
  padding: 10px;
  position: relative;
}

.message-list {
  height: 80vh;
  background: #fff;
  padding: 20px;
  border-radius: 23px;
  overflow-y: scroll;
}

.message-item {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.message-content {
  flex: 1;
}

.username {
  font-size: 14px;
  font-weight: bold;
}

.message {
  font-size: 14px;
  color: #555;
}

.input-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10px;
  display: flex;
  align-items: center;
}

input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 20px;
  margin-right: 10px;
}

button {
  padding: 8px 16px;
  background-color: #007aff;
  color: #fff;
  border-radius: 20px;
}

::-webkit-scrollbar {
  display: none;
}
</style>